from django.test import TestCase
from django.utils.six import BytesIO
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.parsers import JSONParser

from api.serializers.login_serializer import LoginResponseSerializer
from app.models import FMUser, MailingAddress


class BaseTestCase(TestCase):
    def setUp(self):
        encrypted_password = 'adminadmin'  # make_password('adminadmin')
        admin_user = FMUser.objects.create_superuser(username='admin',
                                                     email='admin@example.com',
                                                     password=encrypted_password)
        admin_user.save()
        self.user = admin_user

        self.login('admin', 'adminadmin')

        self.address = MailingAddress.objects.create(user=self.user,
                                                     province=32,
                                                     city=3201,
                                                     area=320102,
                                                     address="XXXXXXX",
                                                     addressee="CCC",
                                                     phone="15652415141",
                                                     is_default=True)

    def login(self, username: str, password: str):
        response = self.client.post('/api/login/',
                                    data='{"username": "' + username + '", "password": "' + password + '"}',
                                    content_type='application/json',
                                    accept_media_type='application/json')
        # data = response.content.decode()
        json_parser = JSONParser()
        data = json_parser.parse(BytesIO(response.content))
        serializer = LoginResponseSerializer(data=data)
        if not serializer.is_valid():
            raise AuthenticationFailed()
        self.access_token = serializer.data['key']

    def tearDown(self):
        pass
